use crate::ast::{ASTNode, Argument, BinOp, Param, SourceLocation};
use crate::config::InterpreterConfig;
use crate::errors::{CompilerError, ErrorKind};
use crate::token::{Token, TokenType};
use std::collections::HashMap;

pub struct Parser {
    tokens: Vec<Token>,
    current: usize,
    file_path: String,
    source: String,
    config: InterpreterConfig,
}

impl Parser {
    pub fn new(tokens: Vec<Token>, file_path: String, source: String) -> Self {
        Parser {
            tokens,
            current: 0,
            file_path,
            source,
            config: InterpreterConfig::default(),
        }
    }

    pub fn new_with_config(
        tokens: Vec<Token>,
        file_path: String,
        source: String,
        config: InterpreterConfig,
    ) -> Self {
        Parser {
            tokens,
            current: 0,
            file_path,
            source,
            config,
        }
    }

    /// 辅助方法：仅在调试模式下输出信息
    fn debug_println(&self, args: std::fmt::Arguments) {
        if self.config.execution_mode.is_debug() {
            eprintln!("{}", args);
        }
    }

    pub fn parse(&mut self) -> Result<ASTNode, CompilerError> {
        let mut chapters = Vec::new();

        // 只解析第一个章节
        if self.current < self.tokens.len() && self.current_token().token_type != TokenType::EOF {
            chapters.push(self.parse_chapter()?);
        }

        if chapters.is_empty() {
            return self.error(
                ErrorKind::SyntaxError,
                "程序必须至少包含一个篇章".to_string(),
                self.current_token(),
                "程序结构不完整，缺少必要的篇章定义".to_string(),
            );
        }

        // 提取第一个章节的三个部分
        if let ASTNode::Chapter {
            name: _,
            intro,
            body,
            conclusion,
            location: _,
        } = &chapters[0]
        {
            Ok(ASTNode::Program {
                preamble: intro.clone(),
                body: body.clone(),
                epilogue: conclusion.clone(),
                location: None,
            })
        } else {
            self.error(
                ErrorKind::SyntaxError,
                "解析错误".to_string(),
                self.current_token(),
                "无法解析程序结构".to_string(),
            )
        }
    }

    fn parse_chapter(&mut self) -> Result<ASTNode, CompilerError> {
        self.expect(TokenType::Chapter)?;
        let name = self.expect_identifier()?;

        self.expect(TokenType::Intro)?;
        let intro = self.parse_block_until(TokenType::End)?;
        self.expect(TokenType::End)?;

        self.expect(TokenType::Body)?;
        let body = self.parse_block_until(TokenType::End)?;
        self.expect(TokenType::End)?;

        self.expect(TokenType::Conclusion)?;
        let conclusion = self.parse_block_until(TokenType::End)?;
        self.expect(TokenType::End)?;

        Ok(ASTNode::Chapter {
            name,
            intro,
            body,
            conclusion,
            location: None,
        })
    }

    fn parse_block_until(&mut self, end: TokenType) -> Result<Vec<ASTNode>, CompilerError> {
        let mut statements = Vec::new();

        while !self.check(&end) && !self.is_at_end() {
            statements.push(self.parse_statement()?);
        }

        Ok(statements)
    }

    fn parse_statement(&mut self) -> Result<ASTNode, CompilerError> {
        self.debug_println(format_args!(
            "DEBUG: parse_statement，当前token: {:?}",
            self.current_token().token_type
        ));
        match &self.current_token().token_type {
            TokenType::Import => self.parse_import(),
            TokenType::Export => self.parse_export(),

            TokenType::Have => {
                // 对于多行变量声明，我们需要特殊处理
                self.parse_var_decl()
            }
            TokenType::Const => self.parse_const_decl(),
            TokenType::Say => self.parse_func_def(),
            TokenType::ClassOf => self.parse_class_def(),
            TokenType::If => self.parse_if(),
            TokenType::While => self.parse_while(),
            TokenType::Do => self.parse_do_while(),
            TokenType::ForEach => self.parse_foreach(),
            TokenType::From => self.parse_for_range(),
            TokenType::Return => self.parse_return(),
            TokenType::Break => {
                self.advance();
                self.expect(TokenType::Period)?;
                Ok(ASTNode::Break(None))
            }
            TokenType::Continue => {
                self.advance();
                self.expect(TokenType::Period)?;
                Ok(ASTNode::Continue(None))
            }
            TokenType::Use => {
                let call = self.parse_call()?;
                self.expect(TokenType::Period)?;
                Ok(call)
            }
            TokenType::SetValue => {
                // 解析 "置 其 结果 于 其 历史" 语句
                self.advance();

                // 解析目标表达式: 其 结果
                let target = self.parse_primary()?;

                // 解析 "于" 关键字
                self.expect(TokenType::At)?;

                // 解析源表达式: 其 历史
                let source = self.parse_primary()?;

                // 生成 ArrayPush 节点
                self.expect(TokenType::Period)?;
                Ok(ASTNode::ArrayPush {
                    array: Box::new(source),
                    value: Box::new(target),
                    location: None,
                })
            }
            TokenType::Identifier(name) if name == "书" || name == "书行" => {
                self.parse_print(name == "书行")
            }
            TokenType::String(_) => {
                // 如果语句以字符串开头，可能是表达式语句
                self.parse_expression_statement()
            }
            TokenType::Identifier(_) => self.parse_assignment_or_expr(),
            TokenType::Its => {
                self.advance();
                let field = self.expect_identifier()?;

                if self.match_token(&TokenType::Is) {
                    let value = self.parse_expression()?;
                    self.expect(TokenType::Period)?;
                    Ok(ASTNode::MemberAssign {
                        object: Box::new(ASTNode::Identifier("其".to_string(), None)),
                        field: field.clone(),
                        value: Box::new(value),
                        location: None,
                    })
                } else {
                    self.expect(TokenType::Period)?;
                    Ok(ASTNode::MemberAccess {
                        object: Box::new(ASTNode::Identifier("其".to_string(), None)),
                        field,
                        location: None,
                    })
                }
            }
            _ => {
                let token = self.current_token();
                self.error(
                    ErrorKind::SyntaxError,
                    format!("意外的语句: {:?}", token),
                    token,
                    "语法错误，遇到了不期望的标记".to_string(),
                )
            }
        }
    }

    fn parse_var_decl(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.expect(TokenType::Have)?;
        let name = self.expect_identifier()?;

        // 检查是否有类型标注（变量名：类型名）
        let mut type_name = None;
        if self.match_token(&TokenType::Colon) {
            type_name = Some(self.expect_type_identifier()?);
        }

        self.expect(TokenType::Thing)?;

        // 支持新语法：有 name：type 者，为 expression。
        let value = if self.match_token(&TokenType::Comma) {
            // 逗号后应该跟着"为"
            self.expect(TokenType::Is)?;
            // 检查是否是跨行字典
            if self.check(&TokenType::Dict) {
                self.parse_expression()?
            } else {
                self.parse_expression()?
            }
        } else if self.match_token(&TokenType::Is) {
            // 直接"为"的情况
            self.parse_expression()?
        } else {
            ASTNode::Null(None)
        };

        // 对于跨行字典，句号可能在字典定义的最后一行
        // 但在多行字典的情况下，字典解析已经消耗了句号
        if !self.check(&TokenType::Period) && !self.check(&TokenType::Newline) {
            return Err(CompilerError::new(
                ErrorKind::SyntaxError,
                "期望句号".to_string(),
                "<input>".to_string(),
                self.current_token().line,
                self.current_token().column,
                "".to_string(),
            ));
        }

        // 只有当前token是句号时才消耗它
        if self.check(&TokenType::Period) {
            self.advance();
        }

        Ok(ASTNode::VarDeclaration {
            name,
            type_name,
            value: Box::new(value),
            location,
        })
    }

    fn parse_const_decl(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.expect(TokenType::Const)?;
        let name = self.expect_identifier()?;

        // 检查是否有类型标注（常量名：类型名）
        let mut type_name = None;
        if self.match_token(&TokenType::Colon) {
            type_name = Some(self.expect_type_identifier()?);
        }

        self.expect(TokenType::Thing)?;
        self.expect(TokenType::Comma)?;
        self.expect(TokenType::Is)?;
        let value = self.parse_expression()?;
        self.expect(TokenType::Period)?;
        Ok(ASTNode::ConstDeclaration {
            name,
            type_name,
            value: Box::new(value),
            location,
        })
    }

    fn parse_expression_statement(&mut self) -> Result<ASTNode, CompilerError> {
        let expr = self.parse_expression()?;
        self.expect(TokenType::Period)?;
        Ok(expr)
    }

    fn parse_assignment_or_expr(&mut self) -> Result<ASTNode, CompilerError> {
        let name = self.expect_identifier()?;

        // 检查是否是复合赋值操作符（加为、减为、乘为、除为）
        if self.match_token(&TokenType::Add) && self.match_token(&TokenType::Is) {
            // 加为：等同于 变量 = 变量 + 表达式
            let start_token = self.current_token().clone();
            let location = Some(SourceLocation::new(start_token.line, start_token.column));

            let value = self.parse_expression()?;
            self.expect(TokenType::Period)?;
            // 创建复合赋值：变量 = 变量 + 值
            let compound_expr = ASTNode::BinaryOp {
                left: Box::new(ASTNode::Identifier(name.clone(), None)),
                op: BinOp::Add,
                right: Box::new(value),
                location: None,
            };
            Ok(ASTNode::Assignment {
                name,
                value: Box::new(compound_expr),
                location,
            })
        } else if self.match_token(&TokenType::Sub) && self.match_token(&TokenType::Is) {
            // 减为：等同于 变量 = 变量 - 表达式
            let start_token = self.current_token().clone();
            let location = Some(SourceLocation::new(start_token.line, start_token.column));

            let value = self.parse_expression()?;
            self.expect(TokenType::Period)?;
            let compound_expr = ASTNode::BinaryOp {
                left: Box::new(ASTNode::Identifier(name.clone(), None)),
                op: BinOp::Sub,
                right: Box::new(value),
                location: None,
            };
            Ok(ASTNode::Assignment {
                name,
                value: Box::new(compound_expr),
                location,
            })
        } else if self.match_token(&TokenType::Mul) && self.match_token(&TokenType::Is) {
            // 乘为：等同于 变量 = 变量 * 表达式
            let start_token = self.current_token().clone();
            let location = Some(SourceLocation::new(start_token.line, start_token.column));

            let value = self.parse_expression()?;
            self.expect(TokenType::Period)?;
            let compound_expr = ASTNode::BinaryOp {
                left: Box::new(ASTNode::Identifier(name.clone(), None)),
                op: BinOp::Mul,
                right: Box::new(value),
                location: None,
            };
            Ok(ASTNode::Assignment {
                name,
                value: Box::new(compound_expr),
                location,
            })
        } else if self.match_token(&TokenType::Div) && self.match_token(&TokenType::Is) {
            // 除为：等同于 变量 = 变量 / 表达式
            let start_token = self.current_token().clone();
            let location = Some(SourceLocation::new(start_token.line, start_token.column));

            let value = self.parse_expression()?;
            self.expect(TokenType::Period)?;
            let compound_expr = ASTNode::BinaryOp {
                left: Box::new(ASTNode::Identifier(name.clone(), None)),
                op: BinOp::Div,
                right: Box::new(value),
                location: None,
            };
            Ok(ASTNode::Assignment {
                name,
                value: Box::new(compound_expr),
                location,
            })
        } else if self.match_token(&TokenType::Is) {
            // 普通赋值：变量 = 表达式
            let start_token = self.current_token().clone();
            let location = Some(SourceLocation::new(start_token.line, start_token.column));

            let value = self.parse_expression()?;
            self.expect(TokenType::Period)?;
            Ok(ASTNode::Assignment {
                name,
                value: Box::new(value),
                location,
            })
        } else {
            // 回退并解析为表达式
            self.current -= 1;
            let expr = self.parse_expression()?;
            self.expect(TokenType::Period)?;
            Ok(expr)
        }
    }

    fn parse_func_def(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.debug_println(format_args!(
            "DEBUG: parse_func_def 开始，当前token: {:?}",
            self.current_token().token_type
        ));
        self.expect(TokenType::Say)?;
        let name = self.expect_identifier()?;

        // 添加调试信息
        self.debug_println(format_args!(
            "DEBUG: 解析函数 {}，当前token: {:?}",
            name,
            self.current_token().token_type
        ));

        // 检查是否有返回类型标注（函数名：类型名）
        let mut return_type = None;
        if self.match_token(&TokenType::Colon) {
            return_type = Some(self.expect_type_identifier()?);
        }

        let mut params = Vec::new();

        self.debug_println(format_args!("DEBUG: 当前token: {:?}", self.current_token()));
        self.debug_println(format_args!(
            "DEBUG: 当前token类型: {:?}",
            self.current_token().token_type
        ));
        self.debug_println(format_args!(
            "DEBUG: 是否为@: {}",
            self.check(&TokenType::At)
        ));
        self.debug_println(format_args!(
            "DEBUG: 是否为标识符: {}",
            self.check_identifier()
        ));
        self.debug_println(format_args!(
            "DEBUG: 是否为于: {}",
            self.check(&TokenType::At)
        ));

        // 解析参数列表 - 支持必需参数、可选参数和关键字参数
        if false {
            // 暂时禁用@符号的参数解析，确保"于"标记的参数列表能正确处理
            params = self.parse_parameter_list()?;
        } else if self.check(&TokenType::At) {
            // 处理使用"于"和"与"的参数定义
            self.debug_println(format_args!("DEBUG: 发现'于'标记，开始解析参数列表"));
            self.advance(); // 跳过"于"

            self.debug_println(format_args!(
                "DEBUG: 跳过'于'后，当前token: {:?}，是否为标识符: {}",
                self.current_token().token_type,
                self.check_identifier()
            ));

            // 解析参数列表，直到遇到换行且下一行不是"与"或"缺则"
            while self.check_identifier() {
                self.debug_println(format_args!(
                    "DEBUG: 解析参数，当前token: {:?}",
                    self.current_token().token_type
                ));
                // 解析参数名
                let param_name = self.expect_identifier()?;
                self.debug_println(format_args!("DEBUG: 解析参数名: {}", param_name));

                // 检查是否有默认值
                let mut default_value = None;
                if self.match_token(&TokenType::DefaultIf) {
                    self.debug_println(format_args!("DEBUG: 发现默认值标记'缺则'"));
                    // 检查下一个token是否是换行符
                    if self.check(&TokenType::Newline) {
                        self.debug_println(format_args!("DEBUG: 默认值在下一行，不支持跨行默认值"));
                        return Err(CompilerError::new(
                            ErrorKind::SyntaxError,
                            "默认值不能跨行".to_string(),
                            "<input>".to_string(),
                            self.current_token().line,
                            self.current_token().column,
                            "".to_string(),
                        ));
                    }
                    default_value = Some(Box::new(self.parse_expression()?));
                    self.debug_println(format_args!(
                        "DEBUG: 解析完默认值，当前token: {:?}",
                        self.current_token().token_type
                    ));
                }

                self.debug_println(format_args!(
                    "DEBUG: 参数 '{}' 解析完成，当前token: {:?}",
                    param_name,
                    self.current_token().token_type
                ));

                // 创建参数
                let param = Param {
                    name: param_name,
                    type_name: None,
                    default_value,
                    is_varargs: false,
                    location: Some(SourceLocation::new(
                        self.current_token().line,
                        self.current_token().column,
                    )),
                };
                params.push(param);

                // 检查是否还有更多参数
                if self.match_token(&TokenType::And) {
                    self.debug_println(format_args!("DEBUG: 发现'与'标记，继续解析下一个参数"));
                    // 检查下一个token是否是标识符，如果不是，则参数列表结束
                    if !self.check_identifier() {
                        self.debug_println(format_args!(
                            "DEBUG: '与'标记后没有标识符，参数列表结束"
                        ));
                        break;
                    }
                    continue;
                } else {
                    self.debug_println(format_args!("DEBUG: 没有'与'标记，参数列表可能结束"));
                    self.debug_println(format_args!(
                        "DEBUG: 当前token: {:?}",
                        self.current_token().token_type
                    ));
                    break;
                }
            }

            self.debug_println(format_args!(
                "DEBUG: 参数解析完成，当前token: {:?}",
                self.current_token().token_type
            ));
        } else if self.check_identifier() {
            // 尝试解析不带@符号的参数列表
            // 检查下一行是否是函数体的开始
            let mut temp_current = self.current;
            let mut found_body_start = false;

            // 向前查找，确定是否是参数列表
            while temp_current < self.tokens.len() {
                let token = &self.tokens[temp_current];
                if token.token_type == TokenType::Newline {
                    // 检查下一行是否是缩进的
                    if temp_current + 1 < self.tokens.len() {
                        let next_token = &self.tokens[temp_current + 1];
                        if next_token.column > token.column {
                            found_body_start = true;
                        }
                    }
                    break;
                }
                temp_current += 1;
            }

            // 如果找到了函数体的开始，则解析参数列表
            if found_body_start {
                params = self.parse_parameter_list()?;
            }
        }

        self.debug_println(format_args!(
            "DEBUG: 参数解析完成，共{}个参数，当前token: {:?}",
            params.len(),
            self.current_token().token_type
        ));
        let body = self.parse_block_until(TokenType::End)?;
        self.expect(TokenType::End)?;

        Ok(ASTNode::FunctionDef {
            name,
            return_type,
            params,
            body,
            location,
        })
    }

    /// 解析参数列表，支持以下语法：
    /// - 必需参数: param_name
    /// - 可选参数: param_name 缺则 default_value
    /// - 可变参数: param_name... (暂未完全实现)
    fn parse_parameter_list(&mut self) -> Result<Vec<Param>, CompilerError> {
        let mut params = Vec::new();

        loop {
            let param_start_token = self.current_token().clone();
            let param_location = Some(SourceLocation::new(
                param_start_token.line,
                param_start_token.column,
            ));

            // 检查是否到达参数列表结束
            if self.check(&TokenType::Colon) {
                break;
            }

            // 检查是否为换行或文件结束
            if self.check(&TokenType::Newline) || self.check(&TokenType::EOF) {
                break;
            }

            // 解析参数名
            let param_name = self.expect_identifier()?;

            // 检查是否有类型标注（参数名：类型名）
            let mut type_name = None;
            if self.match_token(&TokenType::Colon) {
                // 类型标注可以是标识符或基本类型标记
                type_name = Some(self.expect_type_identifier()?);
            }

            // 检查是否为可变参数（...）
            let mut is_varargs = false;
            if self.match_token(&TokenType::Identifier("...".to_string())) {
                is_varargs = true;
            }

            // 检查是否有默认值
            let mut default_value = None;
            if self.match_token(&TokenType::DefaultIf) {
                default_value = Some(Box::new(self.parse_expression()?));
            }

            // 创建参数
            let param = Param {
                name: param_name,
                type_name,
                default_value,
                is_varargs,
                location: param_location,
            };
            params.push(param);

            // 检查是否还有更多参数
            if !self.match_token(&TokenType::And) {
                break;
            }
        }

        Ok(params)
    }

    /// 解析参数列表，支持以下语法：
    /// - 位置参数: expression
    /// - 关键字参数: 参数名 指 expression
    /// 将 Argument 转换为 ASTNode
    #[allow(dead_code)]
    fn argument_to_node(arg: Argument) -> ASTNode {
        match arg {
            Argument::Positional(node, _) => node,
            Argument::Keyword(_, node, _) => node,
        }
    }

    fn parse_argument_list(&mut self) -> Result<Vec<Argument>, CompilerError> {
        self.parse_raw_argument_list()
    }

    fn parse_raw_argument_list(&mut self) -> Result<Vec<Argument>, CompilerError> {
        let mut args = Vec::new();
        let mut _has_positional = false; // 标记是否已遇到位置参数
        let mut keyword_names = std::collections::HashSet::new(); // 记录已使用过的关键字参数名

        if self.config.execution_mode.is_debug() {
            self.debug_println(format_args!(
                "DEBUG: 开始解析参数列表，当前token: {:?}",
                self.current_token().token_type
            ));
        }

        loop {
            let arg_start_token = self.current_token().clone();
            let arg_location = Some(SourceLocation::new(
                arg_start_token.line,
                arg_start_token.column,
            ));

            if self.config.execution_mode.is_debug() {
                self.debug_println(format_args!(
                    "DEBUG: 解析参数，token: {:?}",
                    self.current_token().token_type
                ));
            }

            // 检查是否到达参数列表结束（遇到句号或右括号）
            if self.check(&TokenType::Period) || self.check(&TokenType::RightParen) {
                if self.config.execution_mode.is_debug() {
                    self.debug_println(format_args!("DEBUG: 遇到句号或右括号，结束参数解析"));
                }
                break;
            }

            // 检查是否为关键字参数（"指"关键字）
            if self.check(&TokenType::Specify) {
                self.advance(); // 消费 "指" 关键字
                if self.config.execution_mode.is_debug() {
                    self.debug_println(format_args!("DEBUG: 开始解析关键字参数"));
                }

                // 这是一个关键字参数： 指 参数名 [为] 值
                let param_name = self.expect_identifier()?;
                if self.config.execution_mode.is_debug() {
                    self.debug_println(format_args!("DEBUG: 关键字参数名: {}", param_name.clone()));
                }

                // 检查该关键字参数是否已经使用过
                if keyword_names.contains(&param_name) {
                    let token = self.current_token();
                    let err = CompilerError::new(
                        ErrorKind::SyntaxError,
                        format!("关键字参数 '{}' 已存在", param_name),
                        self.file_path.clone(),
                        token.line,
                        token.column,
                        self.get_line_content(token.line),
                    )
                    .with_description("语法错误，每个关键字参数只能指定一次".to_string());
                    return Err(err);
                }
                keyword_names.insert(param_name.clone());

                // 只支持标准语法： 指 参数名 为 值
                self.expect(TokenType::Is)?;
                let value = self.parse_argument_expression()?;
                args.push(Argument::Keyword(param_name.clone(), value, arg_location));
                if self.config.execution_mode.is_debug() {
                    self.debug_println(format_args!(
                        "DEBUG: 添加关键字参数: {}, 参数总数: {}",
                        param_name,
                        args.len()
                    ));
                }

                // 检查是否还有更多参数 - 如果遇到句号则结束
                if self.check(&TokenType::Period) {
                    if self.config.execution_mode.is_debug() {
                        self.debug_println(format_args!("DEBUG: 关键字参数后遇到句号"));
                    }
                    break;
                } else if self.match_token(&TokenType::And) {
                    // 如果遇到 "与" 关键字，继续解析下一个参数
                    if self.config.execution_mode.is_debug() {
                        self.debug_println(format_args!("DEBUG: 关键字参数后遇到'与'，继续解析"));
                    }
                    continue;
                } else {
                    // 如果既不是句号也不是 "与"，则可能语法有问题，但继续尝试解析
                    if self.config.execution_mode.is_debug() {
                        self.debug_println(format_args!(
                            "DEBUG: 关键字参数后既不是句号也不是'与'，继续尝试解析"
                        ));
                    }
                    continue;
                }
            }

            // 检查是否是位置参数（如果不是关键字参数开头，也不是句号结束）
            if !self.check(&TokenType::Period) && !self.check(&TokenType::Specify) {
                // 这是一个位置参数
                _has_positional = true;
                let value = self.parse_argument_expression()?;
                args.push(Argument::Positional(value, arg_location));
                if self.config.execution_mode.is_debug() {
                    self.debug_println(format_args!(
                        "DEBUG: 添加位置参数，参数总数: {}",
                        args.len()
                    ));
                }

                // 检查是否还有更多参数
                if self.match_token(&TokenType::And) {
                    // 如果后面紧跟关键字参数，但前面已经有位置参数了，
                    // 这是不允许的（位置参数不能出现在关键字参数后面）
                    if let TokenType::Identifier(_) = &self.current_token().token_type {
                        if self
                            .peek_token()
                            .map_or(false, |t| t.token_type == TokenType::Specify)
                        {
                            let token = self.current_token();
                            let err = CompilerError::new(
                                ErrorKind::SyntaxError,
                                "关键字参数不能出现在位置参数后面".to_string(),
                                self.file_path.clone(),
                                token.line,
                                token.column,
                                self.get_line_content(token.line),
                            )
                            .with_description(
                                "语法错误，请将关键字参数移到位置参数前面".to_string(),
                            );
                            return Err(err);
                        }
                    }
                    if self.config.execution_mode.is_debug() {
                        self.debug_println(format_args!("DEBUG: 位置参数后遇到'与'，继续解析"));
                    }
                    continue;
                } else {
                    // 如果后面没有 "与" 关键字，继续循环检查是否是关键字参数或句号
                    // 不直接break，让循环继续处理
                    if self.config.execution_mode.is_debug() {
                        self.debug_println(format_args!(
                            "DEBUG: 位置参数后没有'与'，继续检查下一个token"
                        ));
                    }
                    continue;
                }
            } else {
                // 遇到句号或关键字参数标记，结束参数解析
                if self.config.execution_mode.is_debug() {
                    self.debug_println(format_args!("DEBUG: 遇到句号或关键字参数标记，结束解析"));
                }
                break;
            }
        }

        if self.config.execution_mode.is_debug() {
            self.debug_println(format_args!(
                "DEBUG: 参数解析完成，总共解析到 {} 个参数",
                args.len()
            ));
            for (i, arg) in args.iter().enumerate() {
                match arg {
                    Argument::Positional(_, _) => {
                        self.debug_println(format_args!("DEBUG: 参数 {}: 位置参数", i))
                    }
                    Argument::Keyword(name, _, _) => {
                        self.debug_println(format_args!("DEBUG: 参数 {}: 关键字参数 {}", i, name))
                    }
                }
            }
        }

        Ok(args)
    }

    fn parse_if(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.expect(TokenType::If)?;
        let condition = self.parse_expression()?;
        self.expect(TokenType::Then)?;

        let then_block = self.parse_block_until_any(&[TokenType::Else, TokenType::End])?;

        let mut else_if_conditions = Vec::new();
        let mut else_if_blocks = Vec::new();
        let mut else_block = None;

        // 处理 else 和 elseif
        while self.match_token(&TokenType::Else) {
            // 检查是否是 elseif (否则 如)
            if self.match_token(&TokenType::If) {
                // 这是 elseif: 否则 如 条件 则 ...
                let elseif_condition = self.parse_expression()?;
                self.expect(TokenType::Then)?;
                let elseif_block =
                    self.parse_block_until_any(&[TokenType::Else, TokenType::End])?;

                else_if_conditions.push(Box::new(elseif_condition));
                else_if_blocks.push(elseif_block);
            } else {
                // 这是普通的 else
                else_block = Some(self.parse_block_until(TokenType::End)?);
                break;
            }
        }

        self.expect(TokenType::End)?;

        Ok(ASTNode::If {
            condition: Box::new(condition),
            then_block,
            else_if_conditions,
            else_if_blocks,
            else_block,
            location,
        })
    }

    fn parse_while(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.expect(TokenType::While)?;
        let condition = self.parse_expression()?;

        // 支持两种语法：
        // 1. 当 条件 循环 ... 毕
        // 2. 当 条件 之时 ... 毕
        let body = if self.match_token(&TokenType::WhenTime) {
            // 传统语法：当 条件 之时 ... 毕
            self.parse_block_until(TokenType::End)?
        } else if self.match_token(&TokenType::Loop) {
            // 现代语法：当 条件 循环 ... 毕
            self.parse_block_until(TokenType::End)?
        } else {
            let token = self.current_token();
            return self.error(
                ErrorKind::SyntaxError,
                "期望 '之时' 或 '循环'".to_string(),
                token,
                "语法错误，缺少必要的循环结构标记".to_string(),
            );
        };

        self.expect(TokenType::End)?;

        Ok(ASTNode::While {
            condition: Box::new(condition),
            body,
            location,
        })
    }

    fn parse_foreach(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.expect(TokenType::ForEach)?;

        // 检查是否是字典遍历的键值对解构语法：遍 （k，v） 于 成绩1 循环
        if self.match_token(&TokenType::LeftParen) {
            // 字典遍历的键值对解构语法
            let key_var = self.expect_identifier()?;
            self.expect(TokenType::Comma)?;
            let value_var = self.expect_identifier()?;
            self.expect(TokenType::RightParen)?;
            self.expect(TokenType::At)?;
            let iterable = self.parse_expression()?;
            self.expect(TokenType::Loop)?;
            let body = self.parse_block_until(TokenType::End)?;
            self.expect(TokenType::End)?;

            Ok(ASTNode::ForDictEach {
                key_var,
                value_var,
                iterable: Box::new(iterable),
                body,
                location,
            })
        } else {
            // 普通的遍历语法
            let variable = self.expect_identifier()?;
            self.expect(TokenType::At)?;
            let iterable = self.parse_expression()?;
            self.expect(TokenType::Loop)?;
            let body = self.parse_block_until(TokenType::End)?;
            self.expect(TokenType::End)?;

            Ok(ASTNode::ForEach {
                variable,
                iterable: Box::new(iterable),
                body,
                location,
            })
        }
    }

    fn parse_for_range(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        // 解析 "自 <起始值> 至 <结束值> [步 <步长>] 循环"
        self.expect(TokenType::From)?;
        let start = self.parse_expression()?;
        self.expect(TokenType::To)?;
        let end = self.parse_expression()?;

        // 检查是否有可选的步长
        let step = if self.match_token(&TokenType::Step) {
            Some(Box::new(self.parse_expression()?))
        } else {
            None
        };

        self.expect(TokenType::Loop)?;
        let body = self.parse_block_until(TokenType::End)?;
        self.expect(TokenType::End)?;

        // ForRange循环不需要显式的变量名，使用隐式的循环变量
        Ok(ASTNode::ForRange {
            variable: "i".to_string(), // 默认循环变量名
            start: Box::new(start),
            end: Box::new(end),
            step,
            body,
            location,
        })
    }

    fn parse_do_while(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.expect(TokenType::Do)?;
        let body = self.parse_block_until(TokenType::Until)?;

        self.expect(TokenType::Until)?;
        let condition = self.parse_expression()?;
        self.expect(TokenType::End)?;

        Ok(ASTNode::DoWhile {
            body,
            condition: Box::new(condition),
            location,
        })
    }

    fn parse_return(&mut self) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.expect(TokenType::Return)?;

        let value = if self.check(&TokenType::Period) {
            None
        } else {
            Some(Box::new(self.parse_expression()?))
        };

        self.expect(TokenType::Period)?;
        Ok(ASTNode::Return(value, location))
    }

    fn parse_print(&mut self, is_print_line: bool) -> Result<ASTNode, CompilerError> {
        let start_token = self.current_token().clone();
        let location = Some(SourceLocation::new(start_token.line, start_token.column));

        self.advance(); // 跳过 "书"

        let mut args = vec![self.parse_expression()?];

        while self.match_token(&TokenType::Add) {
            args.push(self.parse_expression()?);
        }

        self.expect(TokenType::Period)?;
        Ok(ASTNode::Print(args, is_print_line, location))
    }

    fn parse_expression(&mut self) -> Result<ASTNode, CompilerError> {
        self.debug_println(format_args!(
            "DEBUG: parse_expression 开始，当前token: {:?}",
            self.current_token().token_type
        ));
        let result = self.parse_logical_or()?;
        self.debug_println(format_args!(
            "DEBUG: parse_expression 完成，当前token: {:?}",
            self.current_token().token_type
        ));
        Ok(result)
    }

    fn parse_logical_or(&mut self) -> Result<ASTNode, CompilerError> {
        self.debug_println(format_args!(
            "DEBUG: parse_logical_or 开始，当前token: {:?}",
            self.current_token().token_type
        ));
        let mut left = self.parse_logical_and()?;

        while self.match_token(&TokenType::LogicOr) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let right = self.parse_logical_and()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: BinOp::Or,
                right: Box::new(right),
                location,
            };
        }

        self.debug_println(format_args!(
            "DEBUG: parse_logical_or 完成，当前token: {:?}",
            self.current_token().token_type
        ));
        Ok(left)
    }

    fn parse_logical_and(&mut self) -> Result<ASTNode, CompilerError> {
        let mut left = self.parse_equality()?;

        while self.match_token(&TokenType::LogicAnd) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let right = self.parse_equality()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: BinOp::And,
                right: Box::new(right),
                location,
            };
        }

        Ok(left)
    }

    fn parse_equality(&mut self) -> Result<ASTNode, CompilerError> {
        let mut left = self.parse_comparison()?;

        while let Some(op) = self.match_tokens(&[TokenType::Eq, TokenType::Ne]) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let bin_op = match op {
                TokenType::Eq => BinOp::Eq,
                TokenType::Ne => BinOp::Ne,
                _ => unreachable!(),
            };

            let right = self.parse_comparison()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: bin_op,
                right: Box::new(right),
                location,
            };
        }

        Ok(left)
    }

    fn parse_comparison(&mut self) -> Result<ASTNode, CompilerError> {
        let mut left = self.parse_term()?;

        while let Some(op) =
            self.match_tokens(&[TokenType::Gt, TokenType::Lt, TokenType::Ge, TokenType::Le])
        {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let bin_op = match op {
                TokenType::Gt => BinOp::Gt,
                TokenType::Lt => BinOp::Lt,
                TokenType::Ge => BinOp::Ge,
                TokenType::Le => BinOp::Le,
                _ => unreachable!(),
            };
            let right = self.parse_term()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: bin_op,
                right: Box::new(right),
                location,
            };
        }

        Ok(left)
    }

    fn parse_term(&mut self) -> Result<ASTNode, CompilerError> {
        let mut left = self.parse_factor()?;

        while let Some(op) = self.match_tokens(&[TokenType::Add, TokenType::Sub]) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let bin_op = match op {
                TokenType::Add => BinOp::Add,
                TokenType::Sub => BinOp::Sub,
                _ => unreachable!(),
            };
            let right = self.parse_factor()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: bin_op,
                right: Box::new(right),
                location,
            };
        }

        Ok(left)
    }

    fn parse_factor(&mut self) -> Result<ASTNode, CompilerError> {
        let mut left = self.parse_unary()?;

        while let Some(op) = self.match_tokens(&[
            TokenType::Mul,
            TokenType::Div,
            TokenType::Mod,
            TokenType::FloorDiv,
        ]) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let bin_op = match op {
                TokenType::Mul => BinOp::Mul,
                TokenType::Div => BinOp::Div,
                TokenType::Mod => BinOp::Mod,
                TokenType::FloorDiv => BinOp::FloorDiv,
                _ => unreachable!(),
            };
            let right = self.parse_unary()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: bin_op,
                right: Box::new(right),
                location,
            };
        }

        Ok(left)
    }

    fn parse_unary(&mut self) -> Result<ASTNode, CompilerError> {
        if self.match_token(&TokenType::LogicNot) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let operand = self.parse_unary()?;
            return Ok(ASTNode::UnaryOp {
                //op: UnOp::Not,
                op: "!".to_string(),
                operand: Box::new(operand),
                location,
            });
        }

        if self.match_token(&TokenType::Sub) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let operand = self.parse_unary()?;
            return Ok(ASTNode::UnaryOp {
                //op: UnOp::Neg,
                op: "-".to_string(),
                operand: Box::new(operand),
                location,
            });
        }

        self.parse_call()
    }

    fn parse_method_target(&mut self) -> Result<ASTNode, CompilerError> {
        // 处理一元运算符
        if self.match_token(&TokenType::LogicNot) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let operand = self.parse_method_target()?;
            return Ok(ASTNode::UnaryOp {
                op: "!".to_string(),
                operand: Box::new(operand),
                location,
            });
        }

        if self.match_token(&TokenType::Sub) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let operand = self.parse_method_target()?;
            return Ok(ASTNode::UnaryOp {
                op: "-".to_string(),
                operand: Box::new(operand),
                location,
            });
        }

        // 解析基本表达式，但不处理"之"标记（因为那是方法调用的标记）
        let token = self.current_token().clone();
        let location = Some(SourceLocation::new(token.line, token.column));

        match &token.token_type {
            TokenType::Integer(n) => {
                let val = *n;
                self.advance();
                Ok(ASTNode::Integer(val, location))
            }
            TokenType::Float(f) => {
                let val = *f;
                self.advance();
                Ok(ASTNode::Float(val, location))
            }
            TokenType::String(s) => {
                let val = s.clone();
                self.advance();
                Ok(ASTNode::String(val, location))
            }
            TokenType::True => {
                self.advance();
                Ok(ASTNode::Boolean(true, location))
            }
            TokenType::False => {
                self.advance();
                Ok(ASTNode::Boolean(false, location))
            }
            TokenType::Null => {
                self.advance();
                Ok(ASTNode::Null(location))
            }
            TokenType::Identifier(name) => {
                let id = name.clone();
                self.advance();
                // 不检查"之"标记，因为那是方法调用的标记
                Ok(ASTNode::Identifier(id, location))
            }
            TokenType::List => {
                self.advance();
                let mut elements = Vec::new();
                if !self.check(&TokenType::Period) {
                    // 检查下一个token是否是换行符，如果是，则不允许跨行列表
                    if self.check(&TokenType::Newline) {
                        return Err(CompilerError::new(
                            ErrorKind::SyntaxError,
                            "列表字面量不能跨行".to_string(),
                            "<input>".to_string(),
                            self.current_token().line,
                            self.current_token().column,
                            "".to_string(),
                        ));
                    }
                    elements.push(self.parse_argument_expression()?);
                    while self.match_token(&TokenType::Comma) {
                        // 检查下一个token是否是换行符，如果是，则不允许跨行列表
                        if self.check(&TokenType::Newline) {
                            return Err(CompilerError::new(
                                ErrorKind::SyntaxError,
                                "列表字面量不能跨行".to_string(),
                                "<input>".to_string(),
                                self.current_token().line,
                                self.current_token().column,
                                "".to_string(),
                            ));
                        }
                        elements.push(self.parse_argument_expression()?);
                    }
                }
                self.expect(TokenType::Period)?;
                Ok(ASTNode::List(elements, location))
            }
            _ => {
                let token = self.current_token();
                self.error(
                    ErrorKind::UnexpectedToken,
                    format!("期望表达式, 但得到 【{:?}】", token.token_type.to_chinese()),
                    token,
                    "语法错误，此处应使用表达式".to_string(),
                )
            }
        }
    }

    fn parse_call(&mut self) -> Result<ASTNode, CompilerError> {
        let mut node;

        if self.match_token(&TokenType::Use) {
            let start_token = self.current_token().clone();
            let location = Some(SourceLocation::new(start_token.line, start_token.column));

            // 解析对象名或表达式
            let target = if self.match_token(&TokenType::Its) {
                // 处理"其"关键字，需要检查后面是否有字段访问
                if matches!(self.current_token().token_type, TokenType::Identifier(_)) {
                    let field = self.expect_identifier()?;
                    ASTNode::MemberAccess {
                        object: Box::new(ASTNode::Identifier("其".to_string(), None)),
                        field,
                        location: None,
                    }
                } else {
                    ASTNode::Identifier("其".to_string(), None)
                }
            } else {
                // 解析表达式而不是仅解析标识符，以支持像"使 -5 之 绝对值"这样的语法
                // 创建一个特殊的目标解析函数，避免递归问题
                self.parse_method_target()?
            };

            // 检查是否是方法调用: 使 对象 之 方法
            if self.match_token(&TokenType::Of) {
                let method = self.expect_identifier()?;

                // 检查是否有"于"关键字，表示有参数
                let mut args = Vec::new();
                if self.match_token(&TokenType::At) {
                    args = self.parse_argument_list_as_nodes()?;
                }

                node = ASTNode::MethodCall {
                    object: Box::new(target),
                    method,
                    args,
                    location,
                };
            } else {
                // 检查是否是函数调用: 使 函数名 于 参数
                if self.match_token(&TokenType::At) {
                    let args = self.parse_argument_list()?;

                    // 创建函数调用节点
                    node = if let ASTNode::Identifier(name, _) = target {
                        ASTNode::FunctionCall {
                            name,
                            args,
                            location,
                        }
                    } else {
                        // 如果不是标识符，这可能是个错误
                        return self.error(
                            ErrorKind::SyntaxError,
                            "函数调用必须是标识符".to_string(),
                            self.current_token(),
                            "语法错误，此处应使用函数名".to_string(),
                        );
                    };
                } else {
                    // 如果既没有"之"也没有"于"，则这个表达式不是函数调用或方法调用
                    // 直接返回解析的目标对象
                    node = target;
                }
            }
        } else {
            node = self.parse_primary()?;
        }

        // 处理数组访问链：表达式 之 索引
        while self.match_token(&TokenType::Of) {
            let index_expr = self.parse_equality()?;
            let location = Some(SourceLocation::new(node.get_line(), node.get_column()));
            node = ASTNode::ArrayAccess {
                array: Box::new(node),
                index: Box::new(index_expr),
                location,
            };
        }

        Ok(node)
    }

    fn parse_primary(&mut self) -> Result<ASTNode, CompilerError> {
        let token = self.current_token().clone();
        let location = Some(SourceLocation::new(token.line, token.column));

        match &token.token_type {
            TokenType::Integer(n) => {
                let val = *n;
                self.advance();
                Ok(ASTNode::Integer(val, location))
            }
            TokenType::Float(f) => {
                let val = *f;
                self.advance();
                Ok(ASTNode::Float(val, location))
            }
            TokenType::String(s) => {
                let val = s.clone();
                self.advance();
                Ok(ASTNode::String(val, location))
            }
            TokenType::StringWithInterpolation(text) => {
                let text_clone = text.clone();
                self.advance();

                // 解析插值部分
                let parsed_parts = self.parse_interpolation_in_text(&text_clone)?;

                Ok(ASTNode::StringInterpolation {
                    parts: parsed_parts,
                    location,
                })
            }
            TokenType::True => {
                self.advance();
                Ok(ASTNode::Boolean(true, location))
            }
            TokenType::False => {
                self.advance();
                Ok(ASTNode::Boolean(false, location))
            }
            TokenType::Null => {
                self.advance();
                Ok(ASTNode::Null(location))
            }
            TokenType::Identifier(name) => {
                let id = name.clone();
                self.advance();
                let mut node = ASTNode::Identifier(id, location);

                // 检查是否是数组访问：标识符 之 表达式
                if self.match_token(&TokenType::Of) {
                    let index_expr = self.parse_expression()?;
                    node = ASTNode::ArrayAccess {
                        array: Box::new(node),
                        index: Box::new(index_expr),
                        location: Some(SourceLocation::new(token.line, token.column)),
                    };
                }

                Ok(node)
            }
            TokenType::List => {
                self.debug_println(format_args!(
                    "DEBUG: 解析List，当前token: {:?}",
                    self.current_token().token_type
                ));
                self.advance();
                self.debug_println(format_args!(
                    "DEBUG: 跳过List后，当前token: {:?}",
                    self.current_token().token_type
                ));
                let mut elements = Vec::new();

                // 检查下一个token是否是句号，如果是，则这是一个空列表
                if self.check(&TokenType::Period) {
                    self.debug_println(format_args!("DEBUG: 下一个token是句号，这是一个空列表"));
                } else if !self.check(&TokenType::Newline) {
                    // 只有当下一个token不是换行符时，才尝试解析列表元素
                    self.debug_println(format_args!(
                        "DEBUG: 下一个token不是句号也不是换行符，尝试解析列表元素"
                    ));
                    elements.push(self.parse_expression()?);
                    while self.match_token(&TokenType::Comma) {
                        elements.push(self.parse_expression()?);
                    }
                } else {
                    self.debug_println(format_args!("DEBUG: 下一个token是换行符，这是一个空列表"));
                }

                self.debug_println(format_args!(
                    "DEBUG: 列表解析完成，当前token: {:?}",
                    self.current_token().token_type
                ));
                Ok(ASTNode::List(elements, location))
            }
            TokenType::Set => {
                self.advance();
                let mut elements = Vec::new();
                if !self.check(&TokenType::Period) {
                    elements.push(self.parse_expression()?);
                    while self.match_token(&TokenType::Comma) {
                        elements.push(self.parse_expression()?);
                    }
                }
                Ok(ASTNode::Set(elements, location))
            }
            TokenType::DictStart => {
                self.advance();
                let mut pairs = Vec::new();

                // 解析字典键值对
                if !self.check(&TokenType::RightBracket) {
                    // 解析第一个键值对
                    let key = self.parse_expression()?;
                    // 期望 "为" 或 ":"
                    if !self.match_token(&TokenType::Is) && !self.match_token(&TokenType::Colon) {
                        let token = self.current_token();
                        return Err(CompilerError::new(
                            ErrorKind::SyntaxError,
                            "期望键值对分隔符".to_string(),
                            "<input>".to_string(),
                            token.line,
                            token.column,
                            "".to_string(),
                        ));
                    }
                    let value = self.parse_expression()?;
                    pairs.push((key, value));

                    // 解析剩余的键值对
                    while self.match_token(&TokenType::Comma) {
                        let key = self.parse_expression()?;
                        // 期望 "为" 或 ":"
                        if !self.match_token(&TokenType::Is) && !self.match_token(&TokenType::Colon)
                        {
                            let token = self.current_token();
                            return Err(CompilerError::new(
                                ErrorKind::SyntaxError,
                                "期望键值对分隔符".to_string(),
                                "<input>".to_string(),
                                token.line,
                                token.column,
                                "".to_string(),
                            ));
                        }
                        let value = self.parse_expression()?;
                        pairs.push((key, value));
                    }
                }

                self.expect(TokenType::RightBracket)?; // 期望 》
                Ok(ASTNode::Dict(pairs, location))
            }
            TokenType::LeftBracket => {
                self.advance();
                let mut elements = Vec::new();

                // 解析列表元素
                if !self.check(&TokenType::RightBracket) {
                    elements.push(self.parse_expression()?);
                    while self.match_token(&TokenType::Comma) {
                        elements.push(self.parse_expression()?);
                    }
                }

                self.expect(TokenType::RightBracket)?; // 期望 ]
                Ok(ASTNode::List(elements, location))
            }
            TokenType::Dict => {
                self.advance();
                let mut pairs = Vec::new();

                // "辞"语法 - 支持跨行字面量
                // 检查是否是跨行字面量语法（下一行是换行且缩进增加）
                let is_multiline = self.check(&TokenType::Newline);

                if is_multiline {
                    // 跨行语法：跳过换行符，解析缩进的键值对
                    self.advance(); // 跳过换行符

                    // 解析跨行键值对，直到遇到非缩进行或结束标记
                    while self.check(&TokenType::Newline) || self.is_indented_line() {
                        if self.check(&TokenType::Newline) {
                            self.advance(); // 跳过空行
                            continue;
                        }

                        // 解析键值对
                        let key = self.parse_expression()?;
                        // 期望 "为"
                        if !self.match_token(&TokenType::Is) {
                            let token = self.current_token();
                            return Err(CompilerError::new(
                                ErrorKind::SyntaxError,
                                "期望键值对分隔符".to_string(),
                                "<input>".to_string(),
                                token.line,
                                token.column,
                                "".to_string(),
                            ));
                        }
                        let value = self.parse_expression()?;
                        pairs.push((key, value));

                        // 检查是否有逗号分隔符（可选）
                        self.match_token(&TokenType::Comma);

                        // 如果是换行符，继续解析下一行
                        if !self.check(&TokenType::Newline) {
                            break;
                        }
                        self.advance(); // 跳过换行符
                    }

                    // 在多行字典的情况下，检查是否有句号
                    self.match_token(&TokenType::Period);
                } else {
                    // 单行语法
                    if !self.check(&TokenType::Period) && !self.check(&TokenType::Comma) {
                        // 解析第一个键值对
                        let key = self.parse_expression()?;
                        // 期望 "为"
                        if !self.match_token(&TokenType::Is) {
                            let token = self.current_token();
                            return Err(CompilerError::new(
                                ErrorKind::SyntaxError,
                                "期望键值对分隔符".to_string(),
                                "<input>".to_string(),
                                token.line,
                                token.column,
                                "".to_string(),
                            ));
                        }
                        let value = self.parse_expression()?;
                        pairs.push((key, value));

                        // 解析剩余的键值对
                        while self.match_token(&TokenType::Comma) {
                            let key = self.parse_expression()?;
                            // 期望 "为"
                            if !self.match_token(&TokenType::Is) {
                                let token = self.current_token();
                                return Err(CompilerError::new(
                                    ErrorKind::SyntaxError,
                                    "期望键值对分隔符".to_string(),
                                    "<input>".to_string(),
                                    token.line,
                                    token.column,
                                    "".to_string(),
                                ));
                            }
                            let value = self.parse_expression()?;
                            pairs.push((key, value));
                        }
                    }
                }

                Ok(ASTNode::Dict(pairs, location))
            }
            TokenType::LeftParen => {
                self.advance();
                let expr = self.parse_expression()?;
                self.expect(TokenType::RightParen)?;
                Ok(expr)
            }
            TokenType::Its => {
                self.advance();
                let field = self.expect_identifier()?;
                Ok(ASTNode::MemberAccess {
                    object: Box::new(ASTNode::Identifier("其".to_string(), None)),
                    field,
                    location,
                })
            }
            TokenType::Use => self.parse_call(),
            _ => self.error(
                ErrorKind::SyntaxError,
                format!("意外的token: {:?}", token),
                &token,
                "语法错误，遇到了不期望的标记".to_string(),
            ),
        }
    }

    fn parse_block_until_any(&mut self, ends: &[TokenType]) -> Result<Vec<ASTNode>, CompilerError> {
        let mut statements = Vec::new();

        while !ends.iter().any(|t| self.check(t)) && !self.is_at_end() {
            statements.push(self.parse_statement()?);
        }

        Ok(statements)
    }

    fn expect(&mut self, expected: TokenType) -> Result<(), CompilerError> {
        if self.check(&expected) {
            self.advance();
            Ok(())
        } else {
            let token = self.current_token();
            let error_msg = format!(
                "期望【{:?}】 , 但得到 【{:?}】",
                expected.to_chinese(),
                token.token_type.to_chinese()
            );
            let description = format!("语法结构不完整，缺少必要的【{:?}】", expected.to_chinese());
            let line = token.line;
            let column = token.column;
            let line_content = self.get_line_content(line);

            Err(CompilerError::new(
                ErrorKind::UnexpectedToken,
                error_msg,
                self.file_path.clone(),
                line,
                column,
                line_content,
            )
            .with_description(description)
            .with_suggestion(match expected {
                TokenType::Identifier(id) => format!("请检查是否使用了正确的标识符: 【{:?}】", id),
                TokenType::String(s) => format!("请使用引号包裹字符串: 【{:?}】", s),
                TokenType::Integer(n) => format!("请使用正确的整数格式: 【{:?}】", n),
                TokenType::Float(f) => format!("请使用正确的小数格式: 【{:?}】", f),
                TokenType::LeftParen => "请添加左括号".to_string(),
                TokenType::RightParen => "请添加右括号".to_string(),
                TokenType::LeftBracket => "请添加左方括号".to_string(),
                TokenType::RightBracket => "请添加右方括号".to_string(),
                TokenType::Period => "请添加句号结束语句".to_string(),
                TokenType::Comma => "请添加逗号分隔元素".to_string(),
                _ => "请检查语法结构是否正确".to_string(),
            }))
        }
    }

    fn expect_identifier(&mut self) -> Result<String, CompilerError> {
        match &self.current_token().token_type {
            TokenType::Identifier(name) => {
                let id = name.clone();
                self.advance();
                Ok(id)
            }
            _ => {
                let token = self.current_token();
                let error_msg =
                    format!("期望标识符, 但得到 【{:?}】", token.token_type.to_chinese());
                let description = format!("语法错误，此处应使用标识符");
                let line = token.line;
                let column = token.column;
                let line_content = self.get_line_content(line);

                Err(CompilerError::new(
                    ErrorKind::UnexpectedToken,
                    error_msg,
                    self.file_path.clone(),
                    line,
                    column,
                    line_content,
                )
                .with_description(description)
                .with_suggestion(match &token.token_type {
                    TokenType::String(s) => format!("请检查是否误将标识符用引号包裹: 【{:?}】", s),
                    TokenType::Integer(n) => format!("请检查是否误用了数字作为标识符: 【{:?}】", n),
                    TokenType::Float(f) => format!("请检查是否误用了数字作为标识符: 【{:?}】", f),
                    _ => "请使用正确的标识符命名".to_string(),
                }))
            }
        }
    }

    /// 期望类型标识符，可以是普通标识符或基本类型标记
    fn expect_type_identifier(&mut self) -> Result<String, CompilerError> {
        let token = self.current_token().clone();
        let type_str = match &token.token_type {
            TokenType::Identifier(name) => {
                let id = name.clone();
                self.advance();
                id
            }
            // 基本类型标记
            TokenType::Integer(_) => {
                self.advance();
                "数".to_string()
            }
            TokenType::String(_) => {
                self.advance();
                "文".to_string()
            }
            TokenType::True | TokenType::False => {
                self.advance();
                "布尔".to_string()
            }
            TokenType::List => {
                self.advance();
                "集".to_string()
            }
            TokenType::Dict => {
                self.advance();
                "辞".to_string()
            }
            TokenType::Set => {
                self.advance();
                "汇".to_string()
            }
            TokenType::Tuple => {
                self.advance();
                "组".to_string()
            }
            TokenType::Null => {
                self.advance();
                "空".to_string()
            }
            _ => {
                let error_msg = format!(
                    "期望类型标识符, 但得到 【{:?}】",
                    token.token_type.to_chinese()
                );
                let description = format!("类型标注错误，此处应使用类型名");
                let line = token.line;
                let column = token.column;
                let line_content = self.get_line_content(line);

                return Err(CompilerError::new(
                    ErrorKind::UnexpectedToken,
                    error_msg,
                    self.file_path.clone(),
                    line,
                    column,
                    line_content,
                )
                .with_description(description)
                .with_suggestion(
                    "请使用有效的类型名，如：数、文、布尔、集、辞、汇、组等".to_string(),
                ));
            }
        };
        Ok(type_str)
    }

    fn match_token(&mut self, token_type: &TokenType) -> bool {
        if self.check(token_type) {
            self.advance();
            true
        } else {
            false
        }
    }

    fn match_tokens(&mut self, types: &[TokenType]) -> Option<TokenType> {
        for t in types {
            if self.check(t) {
                let matched = self.current_token().token_type.clone();
                self.advance();
                return Some(matched);
            }
        }
        None
    }

    fn check(&self, token_type: &TokenType) -> bool {
        if self.is_at_end() {
            return false;
        }
        std::mem::discriminant(&self.current_token().token_type)
            == std::mem::discriminant(token_type)
    }

    /// 检查当前token是否是标识符
    fn check_identifier(&self) -> bool {
        if self.is_at_end() {
            return false;
        }
        matches!(&self.current_token().token_type, TokenType::Identifier(_))
    }

    fn current_token(&self) -> &Token {
        &self.tokens[self.current]
    }

    fn advance(&mut self) {
        if !self.is_at_end() {
            self.current += 1;
        }
    }

    fn peek_token(&self) -> Option<&Token> {
        if self.current + 1 < self.tokens.len() {
            Some(&self.tokens[self.current + 1])
        } else {
            None
        }
    }

    fn is_at_end(&self) -> bool {
        matches!(self.current_token().token_type, TokenType::EOF)
    }

    /// Generate a compiler error with proper context
    /// 解析文本中的插值表达式
    fn parse_interpolation_in_text(
        &mut self,
        text: &str,
    ) -> Result<Vec<crate::ast::StringInterpolationPart>, CompilerError> {
        let mut parts = Vec::new();
        let mut current_text = String::new();
        let mut chars = text.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '《' {
                // 如果有累积的文本，先添加到parts中
                if !current_text.is_empty() {
                    parts.push(crate::ast::StringInterpolationPart::Text(
                        current_text.clone(),
                    ));
                    current_text.clear();
                }

                // 收集插值表达式内容
                let mut interpolation_expr = String::new();
                let mut brace_count = 1; // 已经遇到了一个《

                while let Some(next_ch) = chars.next() {
                    if next_ch == '《' {
                        brace_count += 1;
                        interpolation_expr.push(next_ch);
                    } else if next_ch == '》' {
                        brace_count -= 1;
                        if brace_count == 0 {
                            break; // 插值表达式结束
                        } else {
                            interpolation_expr.push(next_ch);
                        }
                    } else {
                        interpolation_expr.push(next_ch);
                    }
                }

                if brace_count > 0 {
                    return Err(CompilerError::new(
                        ErrorKind::SyntaxError,
                        "插值表达式未闭合".to_string(),
                        self.file_path.clone(),
                        self.current_token().line,
                        self.current_token().column,
                        self.get_line_content(self.current_token().line),
                    ));
                }

                // 使用临时词法分析器解析插值表达式
                // 创建一个禁用字符串插值的配置，避免递归解析
                let mut temp_config = self.config.clone();
                temp_config.enable_string_interpolation = false;

                let mut temp_lexer =
                    crate::lexer::Lexer::new_with_config(&interpolation_expr, temp_config.clone());
                let tokens = match temp_lexer.tokenize() {
                    Ok(tokens) => tokens,
                    Err(e) => {
                        return Err(CompilerError::new(
                            ErrorKind::SyntaxError,
                            format!("插值表达式词法分析失败: {}", e),
                            self.file_path.clone(),
                            self.current_token().line,
                            self.current_token().column,
                            self.get_line_content(self.current_token().line),
                        )
                        .with_description("字符串插值解析错误".to_string()));
                    }
                };

                // 使用临时语法分析器解析插值表达式
                // 创建一个禁用字符串插值的配置，避免递归解析
                let mut temp_config = self.config.clone();
                temp_config.enable_string_interpolation = false;

                let mut temp_parser = Parser::new_with_config(
                    tokens,
                    self.file_path.clone(),
                    interpolation_expr.clone(),
                    temp_config,
                );

                // 解析插值表达式为表达式AST节点
                // 尝试先解析为表达式，如果失败则尝试解析为语句
                let expr = match temp_parser.parse_expression() {
                    Ok(expr) => expr,
                    Err(_) => {
                        // 如果表达式解析失败，尝试解析为语句
                        match temp_parser.parse_statement() {
                            Ok(stmt) => stmt,
                            Err(e) => {
                                return Err(CompilerError::new(
                                    ErrorKind::SyntaxError,
                                    format!("插值表达式语法分析失败: {}", e),
                                    self.file_path.clone(),
                                    self.current_token().line,
                                    self.current_token().column,
                                    self.get_line_content(self.current_token().line),
                                )
                                .with_description("字符串插值解析错误".to_string()));
                            }
                        }
                    }
                };

                parts.push(crate::ast::StringInterpolationPart::Expression(expr));
            } else {
                current_text.push(ch);
            }
        }

        // 添加剩余的文本
        if !current_text.is_empty() {
            parts.push(crate::ast::StringInterpolationPart::Text(current_text));
        }

        Ok(parts)
    }

    fn error(
        &self,
        kind: ErrorKind,
        message: String,
        token: &Token,
        description: String,
    ) -> Result<ASTNode, CompilerError> {
        let line_content = self.get_line_content(token.line);
        Err(CompilerError::new(
            kind,
            message,
            self.file_path.clone(),
            token.line,
            token.column,
            line_content,
        )
        .with_description(description))
    }

    /// Get the content of a specific line from the source code
    fn get_line_content(&self, line_number: usize) -> String {
        // Lines are 1-indexed, so subtract 1 for array access
        self.source
            .lines()
            .nth(line_number - 1)
            .unwrap_or("")
            .to_string()
    }

    fn parse_import(&mut self) -> Result<ASTNode, CompilerError> {
        self.expect(TokenType::Import)?;

        if let TokenType::String(path) = &self.current_token().token_type {
            let path = path.clone();
            self.advance();

            // 检查是否有 "之" 关键字表示选择性导入
            let symbols = if self.match_token(&TokenType::Of) {
                let mut syms = vec![self.expect_identifier()?];
                while self.match_token(&TokenType::Comma) {
                    syms.push(self.expect_identifier()?);
                }
                Some(syms)
            } else {
                None
            };

            self.expect(TokenType::Period)?;
            Ok(ASTNode::Import {
                path,
                symbols,
                location: None,
            })
        } else {
            let token = self.current_token();
            self.error(
                ErrorKind::SyntaxError,
                format!("期望字符串路径, 但得到 {:?}", token.token_type),
                &token,
                "导入语句需要使用字符串路径".to_string(),
            )
        }
    }

    fn parse_export(&mut self) -> Result<ASTNode, CompilerError> {
        self.expect(TokenType::Export)?;
        let mut names = Vec::new();
        names.push(self.expect_identifier()?);
        while self.match_token(&TokenType::Comma) {
            names.push(self.expect_identifier()?);
        }
        self.expect(TokenType::Period)?;
        Ok(ASTNode::Export(names, None))
    }

    fn parse_class_def(&mut self) -> Result<ASTNode, CompilerError> {
        self.expect(TokenType::ClassOf)?;
        let class_name = self.expect_identifier()?;

        let mut fields = Vec::new();
        let mut methods = HashMap::new();

        while !self.check(&TokenType::End) && !self.is_at_end() {
            if self.match_token(&TokenType::Have) {
                // 解析字段: 有 Name [曰/者] [为 Value]
                let name = self.expect_identifier()?;

                // 跳过可选的修饰词
                if self.check(&TokenType::Say) || self.check(&TokenType::Thing) {
                    self.advance();
                }

                // 跳过可选的逗号
                self.match_token(&TokenType::Comma);

                let init = if self.match_token(&TokenType::Is) {
                    Some(self.parse_expression()?)
                } else {
                    None
                };

                // 字段声明不需要句号结尾，但如果用户写了也兼容
                self.match_token(&TokenType::Period);

                fields.push((name, init));
            } else if self.match_token(&TokenType::Say) {
                // 解析方法: 直接在类内部解析，不调用 parse_func_def
                let name = self.expect_identifier()?;

                let mut params = Vec::new();
                if self.match_token(&TokenType::At) {
                    params.push(self.expect_identifier()?);
                    while self.match_token(&TokenType::And) {
                        params.push(self.expect_identifier()?);
                    }
                }

                let body = self.parse_block_until(TokenType::End)?;
                self.expect(TokenType::End)?;

                methods.insert(name, (params, body));
            } else {
                // 跳过其他 token
                self.advance();
            }
        }
        self.expect(TokenType::End)?;

        Ok(ASTNode::ClassDef {
            name: class_name,
            fields,
            methods,
            location: None,
        })
    }

    /// 将 Vec<Argument> 转换为 Vec<ASTNode> 以兼容现有的 FunctionCall 结构
    fn parse_argument_list_as_nodes(&mut self) -> Result<Vec<ASTNode>, CompilerError> {
        let args = self.parse_argument_list()?;
        let mut nodes = Vec::new();

        for arg in args {
            match arg {
                Argument::Positional(node, _) => nodes.push(node),
                Argument::Keyword(_name, value, _) => {
                    // 创建关键字参数的 AST 节点表示
                    nodes.push(value);
                }
            }
        }

        Ok(nodes)
    }

    /// 解析参数表达式，避免递归调用parse_call
    fn parse_argument_expression(&mut self) -> Result<ASTNode, CompilerError> {
        // 解析基本表达式和二元运算符，但不包括函数调用
        self.parse_argument_term()
    }

    /// 解析参数项，支持基本表达式和二元运算符
    fn parse_argument_term(&mut self) -> Result<ASTNode, CompilerError> {
        let mut left = self.parse_argument_factor()?;

        while let Some(op) = self.match_tokens(&[TokenType::Add, TokenType::Sub]) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let bin_op = match op {
                TokenType::Add => BinOp::Add,
                TokenType::Sub => BinOp::Sub,
                _ => unreachable!(),
            };
            let right = self.parse_argument_factor()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: bin_op,
                right: Box::new(right),
                location,
            };
        }

        Ok(left)
    }

    /// 解析参数因子，支持基本表达式和一元运算符
    fn parse_argument_factor(&mut self) -> Result<ASTNode, CompilerError> {
        let mut left = self.parse_argument_unary()?;

        while let Some(op) = self.match_tokens(&[
            TokenType::Mul,
            TokenType::Div,
            TokenType::Mod,
            TokenType::FloorDiv,
        ]) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let bin_op = match op {
                TokenType::Mul => BinOp::Mul,
                TokenType::Div => BinOp::Div,
                TokenType::Mod => BinOp::Mod,
                TokenType::FloorDiv => BinOp::FloorDiv,
                _ => unreachable!(),
            };
            let right = self.parse_argument_unary()?;
            left = ASTNode::BinaryOp {
                left: Box::new(left),
                op: bin_op,
                right: Box::new(right),
                location,
            };
        }

        Ok(left)
    }

    /// 解析参数一元表达式，支持一元运算符和基本表达式
    fn parse_argument_unary(&mut self) -> Result<ASTNode, CompilerError> {
        if self.match_token(&TokenType::LogicNot) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let operand = self.parse_argument_unary()?;
            return Ok(ASTNode::UnaryOp {
                op: "!".to_string(),
                operand: Box::new(operand),
                location,
            });
        }

        if self.match_token(&TokenType::Sub) {
            let op_token = self.current_token().clone();
            let location = Some(SourceLocation::new(op_token.line, op_token.column));
            let operand = self.parse_argument_unary()?;
            return Ok(ASTNode::UnaryOp {
                op: "-".to_string(),
                operand: Box::new(operand),
                location,
            });
        }

        // 解析基本表达式，但不包括函数调用
        self.parse_primary()
    }

    /// 检查当前行是否是缩进的（相对于前一行）
    fn is_indented_line(&self) -> bool {
        if self.current >= self.tokens.len() {
            return false;
        }

        let current_token = &self.tokens[self.current];

        // 如果当前token是换行符，则不是缩进行
        if current_token.token_type == TokenType::Newline {
            return false;
        }

        // 查找前一个非换行符token
        let mut prev_index = self.current.saturating_sub(1);
        while prev_index > 0 && self.tokens[prev_index].token_type == TokenType::Newline {
            prev_index -= 1;
        }

        // 如果没有前一个token，则不是缩进行
        if prev_index == 0 && self.tokens[prev_index].token_type == TokenType::Newline {
            return false;
        }

        // 比较当前行和前一行的缩进
        let prev_token = &self.tokens[prev_index];
        current_token.column > prev_token.column
    }
}
